using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PopupManager
{
    public interface PopupInitter
    {
        GameObject GetPopupObject();
        bool Init(GameObject go);
    }

    private Queue<PopupInitter> popupQueue = new Queue<PopupInitter>();

    private static PopupManager sObj = null;
    public static PopupManager Instance()
    {
        if(null == sObj)
        {
            sObj = new PopupManager();
        }  
        return sObj;
    }

    private bool ShowPopup(PopupInitter action)
    {
        var root = GameUtils.Instance().UiRoot;
        if(null == root)
        {
            Debug.LogError("not find ui root");
            return false;
        }

        GameObject go = action.GetPopupObject();
        if(null == go)
        {
            return false;
        }

        go.transform.SetParent(root.transform);
        var rectTran = (RectTransform)go.transform;
        rectTran.offsetMin = new Vector2(0,0);
        rectTran.offsetMax = new Vector2(0,0);

        if(!action.Init(go))
        {
            GameObject.Destroy(go);
            return false;
        }

        return true;
    }

    public bool Push(PopupInitter action)
    {
        if(0 == popupQueue.Count)
        {
            if(!ShowPopup(action))
            {
                popupQueue.Dequeue();
                return false;
            }
        }

        popupQueue.Enqueue(action);

        return true;
    }

    public bool PopNext()
    {
        bool ret = true;

        popupQueue.Dequeue();

        while(popupQueue.Count > 0)
        {
            PopupInitter action = popupQueue.ToArray()[0];
            if(!ShowPopup(action))
            {
                ret = false;
                popupQueue.Dequeue();
                continue;
            }
            break;
        }
        return ret;
    }
}